const { getApiUrl } = require("./config");
// 软件列表数据
let softwareList = [];

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    // 加载软件列表
    loadSoftwareList();
});

// 在文件上传处理函数中添加分块上传逻辑
async function uploadFile(file) {
    const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB 分块
    const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
    const identifier = Date.now().toString(); // 文件唯一标识符

    for (let i = 0; i < totalChunks; i++) {
        const chunk = file.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
        const formData = new FormData();
        formData.append('chunk', chunk);

        try {
            const response = await fetch(getApiUrl('upload-chunk'), {
                method: 'POST',
                headers: {
                    'X-Chunk-Index': i.toString(),
                    'X-Total-Chunks': totalChunks.toString(),
                    'X-Identifier': identifier,
                    'X-Filename': file.name,
                    'X-Software-Name': document.getElementById('softwareName').value,
                    'X-Version': document.getElementById('version').value,
                    'X-Description': document.getElementById('description').value
                },
                body: formData
            });

            if (!response.ok) {
                throw new Error('分块上传失败');
            }

            // 更新进度条
            const progress = ((i + 1) / totalChunks) * 100;
            document.getElementById('uploadProgress').value = progress;

            // 如果是最后一个分块，处理响应
            if (i === totalChunks - 1) {
                const result = await response.json();
                if (result.software) {
                    softwareList.push(result.software);
                    updateSoftwareList();
                }
            }

        } catch (error) {
            console.error('上传错误:', error);
            showAlert('上传失败，请重试', 'error');
            return false;
        }
    }

    return true;
}

// 添加版本号验证函数
function validateVersion(version) {
    // 匹配格式：v1.2.3 或 1.2.3 或 1.2 或 1.0.0-alpha 等
    const versionPattern = /^v?\d+\.\d+(\.\d+)?(-[a-zA-Z0-9]+)?$/;
    return versionPattern.test(version);
}

// 修改表单提交处理
document.getElementById('uploadForm').addEventListener('submit', async function(event) {
    event.preventDefault();

    const version = document.getElementById('version').value;
    if (!validateVersion(version)) {
        showAlert('请输入正确的版本号格式，例如：1.0.0 或 v1.0.0', 'error');
        return;
    }

    const file = document.getElementById('installPackage').files[0];
    
    // 检查文件类型
    const allowedTypes = ['application/x-zip-compressed', 'application/zip', 'application/x-rar-compressed'];
    if (!allowedTypes.includes(file.type)) {
        showAlert('请选择有效的压缩文件（ZIP/RAR）', 'error');
        return;
    }

    // 检查文件大小（100MB限制）
    if (file.size > 100 * 1024 * 1024) {
        showAlert('文件大小不能超过100MB', 'error');
        return;
    }

    document.getElementById('progressContainer').style.display = 'block';

    try {
        const uploadSuccess = await uploadFile(file);
        if (uploadSuccess) {
            showAlert('文件上传成功！', 'success');
            document.getElementById('uploadForm').reset();
            loadSoftwareList();
        }
    } catch (error) {
        console.error('上传错误:', error);
        showAlert('上传失败，请重试', 'error');
    } finally {
        document.getElementById('progressContainer').style.display = 'none';
    }
});

// 更新软件列表��示
function updateSoftwareList() {
    const tbody = document.getElementById('softwareList');
    tbody.innerHTML = '';
    
    softwareList.forEach(software => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${software.name}</td>
            <td>${software.version}</td>
            <td>${software.description}</td>
            <td>
                <button onclick="editSoftware(${software.id})">编辑</button>
                <button onclick="deleteSoftware(${software.id})">删除</button>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

// 加载软件列表
function loadSoftwareList() {
    // 从服务器获取数据
    fetch(getApiUrl('software-list'))
        .then(response => response.json())
        .then(data => {
            softwareList = data;
            updateSoftwareList();
        })
        .catch(error => console.error('获取软件列表失败:', error));
}

// 添加显示提示的函数
function showAlert(message, type) {
    console.log('显示提示:', message, type); // 添加调试日志
    const alertBox = document.getElementById('alertBox');
    if (!alertBox) {
        console.error('未找到 alertBox 元素');
        return;
    }
    
    alertBox.textContent = message;
    alertBox.className = `alert alert-${type}`;
    alertBox.style.display = 'block';
    
    // 3秒后自动隐藏
    setTimeout(() => {
        alertBox.style.animation = 'fadeOut 0.5s';
        setTimeout(() => {
            alertBox.style.display = 'none';
            alertBox.style.animation = '';
        }, 500);
    }, 3000);
}

// 添加编辑功能相关代码
function editSoftware(id) {
    const software = softwareList.find(s => s.id === id);
    if (!software) {
        showAlert('软件不存在', 'error');
        return;
    }

    // 创建编辑表单
    const editForm = document.createElement('div');
    editForm.className = 'edit-form';
    editForm.innerHTML = `
        <div class="modal">
            <div class="modal-content">
                <h3>编辑软件信息</h3>
                <div>
                    <label>软件名称：</label>
                    <input type="text" id="editName" value="${software.name}" required>
                </div>
                <div>
                    <label>版本号：</label>
                    <input type="text" id="editVersion" value="${software.version}" required 
                           placeholder="例如：1.0.0 或 v1.0.0">
                    <small style="color: #666; display: block; margin-top: 5px;">
                        版本号格式：主版本号.次版本号.修订号 (例如：1.0.0)
                    </small>
                </div>
                <div>
                    <label>描述：</label>
                    <textarea id="editDescription">${software.description || ''}</textarea>
                </div>
                <div class="modal-buttons">
                    <button onclick="saveEdit(${software.id})">保存</button>
                    <button onclick="cancelEdit()">取消</button>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(editForm);
}

async function saveEdit(id) {
    const name = document.getElementById('editName').value;
    const version = document.getElementById('editVersion').value;
    const description = document.getElementById('editDescription').value;

    if (!validateVersion(version)) {
        showAlert('请输入正确的版本号格式，例如：1.0.0 或 v1.0.0', 'error');
        return;
    }

    try {
        const response = await fetch(getApiUrl('software/${id}'), {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name, version, description })
        });

        if (!response.ok) {
            throw new Error('更新失败');
        }

        const result = await response.json();
        
        // 更新本地列表
        const index = softwareList.findIndex(s => s.id === id);
        if (index !== -1) {
            softwareList[index] = result.software;
            updateSoftwareList();
        }

        showAlert('软件信息更新成功', 'success');
        cancelEdit();
    } catch (error) {
        console.error('更新错误:', error);
        showAlert('更新失败，请重试', 'error');
    }
}

function cancelEdit() {
    const editForm = document.querySelector('.edit-form');
    if (editForm) {
        editForm.remove();
    }
} 